package edu.cicese.alz;

import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JTextFieldDateEditor;
import edu.cicese.alz.swing.SwingUtil;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.util.Locale;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 27/06/12
 * Time: 12:38 PM
 */
public class DateChooser extends JDateChooser {

	public DateChooser(String date, String dateFormat) {
		super();
		setLocale(Locale.ENGLISH);
		setDateFormatString(dateFormat);
		try {
			setDate(SwingUtil.calendarDateFormat.parse(date));
		} catch (ParseException e) { /*ignored*/ }
//		setPreferredSize(new Dimension(50, 20));
		setMaximumSize(new Dimension(95, 20));

		JButton calendarButton = getCalendarButton();
		calendarButton.setIcon(getIcon("calendar_small"));
		calendarButton.setFocusPainted(false);
		calendarButton.setMargin(SwingUtil.insetsEmpty);
		calendarButton.setBorder(SwingUtil.borderEmpty1);

		calendarButton.addMouseListener(new CalendarButtonMouseListener(calendarButton, SwingUtil.colors2));

		Component[] components = getComponents();
		for (Component component : components) {
			if (component instanceof JTextFieldDateEditor) {
				JTextFieldDateEditor textFieldDateEditor = ((JTextFieldDateEditor) component);
				textFieldDateEditor.setBorder(SwingUtil.borderTextField);
				textFieldDateEditor.setFont(SwingUtil.fontMain);
			}
		}
	}

	public Icon getIcon(String iconName) {
		return new ImageIcon(getClass().getClassLoader().getResource("icons/" + iconName + ".png"));
	}

	class CalendarButtonMouseListener extends MouseAdapter {

		private JButton button;
		private Color[] colors;

		public CalendarButtonMouseListener(JButton button, Color[] colors) {
			this.button = button;
			this.colors = colors;
		}

		public void mouseEntered(MouseEvent evt) {
			if (button.isEnabled()) {
				button.setBackground(colors[1]);
				button.setBorder(BorderFactory.createLineBorder(colors[2]));
			}
		}

		public void mouseExited(MouseEvent evt) {
			button.setBackground(colors[0]);
			button.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
		}

		public void mousePressed(MouseEvent evt) {
			if (button.isEnabled()) {
				button.setBorder(BorderFactory.createLineBorder(colors[3]));
			}
		}

		public void mouseClicked(MouseEvent evt) {
			if (button.isEnabled()) {
				button.setBorder(BorderFactory.createLineBorder(colors[2]));
			}
		}
	}

}
